package com.jianzhile.jobs.activities.add;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.TextView;

import com.gugalor.adapter.AlbumGridViewAdapter;
import com.jianzhile.jobs.R;
import com.jianzhile.jobs.base.BaseActivity;
import com.jianzhile.jobs.utils.AlbumHelper;
import com.jianzhile.jobs.utils.Const;
import com.jianzhile.jobs.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * 相册
 */
public class AlbumActivity extends BaseActivity implements OnClickListener,
		AlbumGridViewAdapter.OnItemClickListener {

	private static final String TAG = "AlbumActivity";
	// 获取图片
	private static final int CAPTURE_PHOTO_COMPLETE = 1;
	// title bar 照片
	private TextView mPhotoTv;
	// title
	private TextView mTitleTv;
	// title bar 取消
	private TextView mCancelTv;
	// 相片GridView
	private GridView mPhotoGrid;
	// GridView适配器
	private AlbumGridViewAdapter mAdapter;
	// 相片数据list
	private ArrayList<String> mDataList;
	// 被选中的相册数据list
	private ArrayList<String> mSelectedDataList = new ArrayList<String>();
	// 确定按钮
	private TextView mOkTv;
	// 标题
	private String mTitle;
	// 预览按钮
	private TextView mPreviewTv;
	// 是否来自publish
	private boolean mIsFromPublish = false;
	// topic id
	private String mTopicId = "";


	private void init() {
		mTitleTv = (TextView) findViewById(R.id.title_tv);
		mPhotoTv = (TextView) findViewById(R.id.photo_tv);
		mCancelTv = (TextView) findViewById(R.id.cancel_tv);
		mPhotoGrid = (GridView) findViewById(R.id.photo_grid);
		mPreviewTv = (TextView) findViewById(R.id.preview_tv);
		mOkTv = (TextView) findViewById(R.id.ok_tv);
		mTitle = getString(R.string.gallery);
	}


	private void initEvents() {
		mPhotoTv.setOnClickListener(this);
		mCancelTv.setOnClickListener(this);
		mPreviewTv.setOnClickListener(this);
		mOkTv.setOnClickListener(this);
		mPhotoGrid.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				} else {
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
								 int visibleItemCount, int totalItemCount) {

			}
		});
	}

	/**
	 * 根据bucketId获取图片数据,当bucketId为null时，是获取所有图片
	 */
	private void loadPhotos(final String bucketId) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				mDataList = AlbumHelper.getPhotoPath(getContentResolver(),
						bucketId);
				// 扫描图片完成
				mHandler.sendEmptyMessage(CAPTURE_PHOTO_COMPLETE);
			}
		}).start();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	/**
	 * 处理扫描相册
	 */
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case CAPTURE_PHOTO_COMPLETE:
				// 初始化显示
				initDisplay();
				break;

			default:
				break;
			}
		}

	};

	/**
	 * 初始化显示
	 */
	private void initDisplay() {
		if (null == mSelectedDataList) {
			mSelectedDataList = new ArrayList<>();
		}
		mAdapter = new AlbumGridViewAdapter(this, mDataList, mSelectedDataList);
		mPhotoGrid.setAdapter(mAdapter);

		// adapter设置回调
		mAdapter.setOnItemClickListener(this);

		// 设置确定按钮的显示
		initOkBtnDisplay();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.photo_tv:
			// 照片
			launchAlbumsChooserActivity();
			break;
		case R.id.cancel_tv:
			if (mIsFromPublish) {
				Intent intent = new Intent();
				intent.putExtra(Const.SELECTED_PATH_EXTRA, mSelectedDataList);
				intent.putExtra(Const.TOPIC_ID_EXTRA, mTopicId);
				// 如果是从PublishActivity过来的，需要回调
				this.setResult(Activity.RESULT_CANCELED, intent);
				this.finish();
			} else {
				// 取消
				this.finish();
			}
			break;
		case R.id.preview_tv:
			// 预览按钮
			launchPreviewActivity();
			break;
		case R.id.ok_tv:
			// 确定按钮
			launchPublishActivity();
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(CheckBox toggleButton, int position, String path,
							boolean isChecked) {
		if (mSelectedDataList.size() >= Const.PHOTO_NUM_SELECT) {
			toggleButton.setChecked(false);
			if (!removePath(path)) {
				ToastUtils.showCenterToast(
						AlbumActivity.this,
						getString(R.string.album_choose_file_nums_tip,
								Const.PHOTO_NUM_SELECT));
			}
			return;
		}
		if (isChecked) {
			if (!mSelectedDataList.contains(path)) {
				mSelectedDataList.add(path);
				// 设置确定按钮的显示
				initOkBtnDisplay();
			}
		} else {
			removePath(path);
		}
	}

	private boolean removePath(String path) {
		if (mSelectedDataList.contains(path)) {
			// 用iterator方式移除path
			Iterator<String> iterator = mSelectedDataList.iterator();
			while (iterator.hasNext()) {
				String currentPath = (String) iterator.next();
				if (path.equals(currentPath)) {
					iterator.remove();
				}
			}
			// 设置确定按钮的显示
			initOkBtnDisplay();
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 设置确定按钮的显示
	 */
	private void initOkBtnDisplay() {
		if (null == mSelectedDataList) {
			return;
		}
		int nums = (mSelectedDataList.isEmpty()) ? 0 : mSelectedDataList.size();
		if (nums > 0) {
			mPreviewTv.setEnabled(true);
			mOkTv.setEnabled(true);
			mOkTv.setText(getString(R.string.ok_with_num, nums + ""));
		} else {
			mPreviewTv.setEnabled(false);
			mOkTv.setEnabled(false);
			mOkTv.setText(getString(R.string.sure));
		}
	}

	/**
	 * 相册 选择
	 */
	private void launchAlbumsChooserActivity() {
		Intent intent = new Intent(this, AlbumsChooserActivity.class);
		startActivityForResult(intent, Const.CHOOSE_ALBUM_REQUEST_CODE);
		overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
	}

	/**
	 * 查看大图
	 */
	private void launchPreviewActivity() {
		 Intent intent = new Intent(this, PreviewActivity.class);
		 intent.putExtra(Const.SELECTED_PATH_EXTRA, mSelectedDataList);
		 this.startActivity(intent);
		 overridePendingTransition(R.anim.push_bottom_in,
		 R.anim.push_bottom_out);
	}

	/**
	 * 发表照片 activity
	 */
	private void launchPublishActivity() {
		Intent intent = new Intent();
		intent.putExtra(Const.SELECTED_PATH_EXTRA, mSelectedDataList);
		intent.putExtra(Const.TOPIC_ID_EXTRA, mTopicId);
		// 如果是从PublishActivity过来的，需要回调
		setResult(Activity.RESULT_OK, intent);
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Const.CHOOSE_ALBUM_REQUEST_CODE:
			// 选择相册，回来
			handleAlbumChooser(resultCode, data);
			break;

		default:
			break;
		}
	}

	/**
	 * 选择相册后回来
	 */
	private void handleAlbumChooser(int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			mTitle = data.getStringExtra(Const.TITLE_EXTRA);
			String bucketId = data.getStringExtra(Const.BUCKET_ID_EXTRA);
			if (TextUtils.isEmpty(mTitle)) {
				mTitleTv.setText(mTitle + "");
			}

			// 重新加载图片
			loadPhotos(bucketId);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();
		if (mIsFromPublish) {
			Intent intent = new Intent();
			intent.putExtra(Const.SELECTED_PATH_EXTRA, mSelectedDataList);
			intent.putExtra(Const.TOPIC_ID_EXTRA, mTopicId);
			// 如果是从PublishActivity过来的，需要回调
			this.setResult(Activity.RESULT_CANCELED, intent);
			this.finish();
		} else {
			// 取消
			this.finish();
		}
	}

	@Override
	public void initView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_album);
		init();
		initEvents();
		// 获取相片数据
		loadPhotos(null);
	}

	@Override
	public void setListener() {

	}

	@SuppressWarnings("unchecked")
	@Override
	public void initData() {
		Intent intent = getIntent();
		if (null != intent) {
			mIsFromPublish = intent.getBooleanExtra(Const.FROM_PUBLISH_EXTRA,
					false);
			if (mIsFromPublish) {
				// 从PublishActivity过来的才需要获取mSelectedDataList
				mSelectedDataList = (ArrayList<String>) intent
						.getSerializableExtra(Const.SELECTED_PATH_EXTRA);
			}
			mTopicId = intent.getStringExtra(Const.TOPIC_ID_EXTRA);
		}
	}

}
